/**
 * Indicated if the social security number is valid
 * @private
 */
var validSocialSecurityNumber = false;
/**
 * Indicated if the distance is valid
 * @private
 */
var validDistance = true;

/**
 * the id of the DOM element
 * @const
 */
var maxDistanceId = "#maxDistance";

/**
 * the id of the DOM element
 * @const
 */
var socialSecurityNumber = "#socialSecurityNumberInput";

/**
 * the id of the DOM element
 * @const
 */
var surgeryTypeSelect = "#typeSelect";

/**
 * the id of the placeholder element
 * @const
 */
var patientNamePlaceholderId = "#patientNamePlaceholder";

//init code
HEALTH.setRole(HEALTH_ROLE_DOCTOR);
$(document).ready(function() {
	HEALTH.initPage("dataGrid", ["day","start","end","type","hospital","patient",function (dataSource, type, param) {
		return "<button class='btn btn-danger' onclick='cancelReservation(" + dataSource["id"] + ");'>Reservierung stornieren</button>";
	}]);

	$('#myModal').on('show', function () {
		HEALTH.addOptions('reservation/types', 'typeSelect');
		$(socialSecurityNumber).change(function() {
			var input = $(socialSecurityNumber);
			var inputText = input.val();
			if (inputText.length != 4 || !HEALTH.isNumber(inputText)) {
				validSocialSecurityNumber = false;
				addValidationError(input);
				//remove the patient's name
				$(patientNamePlaceholderId).text('');
			} else {
				$(patientNamePlaceholderId).text('Überprüfe Sozialversicherungsnummer...');
				jQuery.ajax({
					url:'reservation/validate?socialSecurityNumber=' + inputText,
					type:'GET',
					dataType:'text',
					success:function(json) {
						if (json == null || !json) {
							validSocialSecurityNumber = false;
							addValidationError(input);
							$(patientNamePlaceholderId).text('');
						} else {
							validSocialSecurityNumber = true;
							removeValidationError(input);
							//Show the name of the patient
							$(patientNamePlaceholderId).text(json);
						}
					},
					error: function(jqXHR, textStatus, errorThrown) {
						$(patientNamePlaceholderId).text('');
					}
				});
			}
		});
		$(maxDistanceId).change(function() {
			var input = $(maxDistanceId);
			var inputValue = input.val();
			if (HEALTH.isNumber(inputValue) && inputValue > 0) {
				validDistance = true;
				removeValidationError(input);
			} else {
				validDistance = false;
				addValidationError(input);
			}
		});
	});
});

/**
 * Decorated the input element with error/success class
 * @param input the input element
 * @param error validation error or not
 * @private
 */
function setValidationResult(input, error) {
	if (error) {
		input.parent("div.control-group").addClass('error');
		input.parent("div.control-group").removeClass('success');
	} else {
		input.parent("div.control-group").removeClass('error');
		input.parent("div.control-group").addClass('success');
	}
}

/**
 * Increase the error counter
 * @private
 */
function addValidationError(input) {
	setValidationResult(input, true);
	revalidateButtonState();
}

/**
 * Decrease the error counter
 * @private
 */
function removeValidationError(input) {
	setValidationResult(input, false);
	revalidateButtonState();
}

/**
 * Revalidate the enabled/disabled state of the button
 * @private
 */
function revalidateButtonState() {
	if (validSocialSecurityNumber && validDistance)
		$("#submitButton").removeAttr("disabled");
	else
		$("#submitButton").attr("disabled", "true");
}


/**
 * Submit the rservation form
 */
function submitReservationForm() {
	$("#submitButton").attr("disabled", "true");
	$.ajax({
		url:"reservation/request",
		type:'GET',
		dataType: 'text',
		data: {"patient":$(socialSecurityNumber).val(),"maxKilometers":$(maxDistanceId).val(),"surgeryType":$(surgeryTypeSelect).val()},
		success: function(json) {
			if (json == "ok") {
				$("#myModal").modal("hide");
				//restore default values
				$(socialSecurityNumber).val('');
				$(patientNamePlaceholderId).text('');
				$(maxDistanceId).val('30');
				$(socialSecurityNumber).parent().removeClass('success');
				$(maxDistanceId).parent().removeClass('success');
				//show global notification
				HEALTH.addNotification("success", "Reservierungsantrag gespeichert", "Der Reservierungsantrag wurde zur weiteren Verarbeitung entgegengenommen");
			}
			else {
				$("#submitButton").removeAttr("disabled");
				HEALTH.showNotification("errorMessages", "error", "Fehler beim Speichern des Antrags", "Beim Speichern des Reservierungsantrags ist ein Fehler auftreten. Bitte versuchen Sie es erneut oder wenden Sie sich an Ihren Administrator");
			}
		},
		error: function(jqXHR, textStatus, errorThrown) {
			HEALTH.showNotification("errorMessages", "error", "Fehler bei der Serverkommunikation", "Bei der Kommunikation mit dem HEALTH Server ist ein Fehler aufgetreten. Bitte überprüfen Sie Ihre Internetverbindung oder wenden Sie sich an Ihren Administrator.");
			$("#submitButton").removeAttr("disabled");
		}
	});
}

/**
 * Cancel the reservation of the given slot
 * @param slotID the reserved slot
 */
function cancelReservation(slotID) {
	if (confirm("Wollen Sie diese Reservierung wirklich stornieren?")) {
		HEALTH.callSetter("reservation/cancel", {"id":slotID});
		HEALTH.reloadMainTable();
	}
}

//export the submitReservationForm function - this function should be called by the HTML file
HEALTH.exportSymbol('submitReservationForm', submitReservationForm);
//export the cancel function
HEALTH.exportSymbol('cancelReservation', cancelReservation);
